package cn.hchaojie.camp.day10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

public class DemoFileOutputStream {
	@Test
	public void testStream() {
		File dir = new File("data/day10");
		
		dir.mkdirs();

		File file = new File(dir, "file.txt");

//		FileOutputStream fo = null;
//		try {
//			// append 往后面添加
//			fo = new FileOutputStream(file, true);
//			fo.write('C');		// int > char
//			fo.write("FFF".getBytes());
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			if (fo != null) {
//				try {
//					fo.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
		
		try (FileOutputStream fo = new FileOutputStream(file, true)) {
			// append 往后面添加
			fo.write('C');		// int > char
			fo.write("FFF".getBytes());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	// inputstream 读文件
	@Test
	public void testInputStream() {
		File dir = new File("data/day10");
		File file = new File(dir, "file.txt");
		
		try (FileInputStream fi = new FileInputStream(file)) {
			// read()，每次读取一个字符
//			int c = fi.read();
//			System.out.println((char) c);
//
//			c = fi.read();
//			System.out.println((char) c);
			
			byte[] bytes = new byte[100];
			
			int count = fi.read(bytes);
			System.out.println("有几个字符：" + count);
			System.out.println(new String(bytes, 0, count));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testChar() {
		System.out.println((int) 'A');
		System.out.println('A' - 'B');
		System.out.println((char) ('A' + 25));
	}
	
	@Test
	public void testFileCopy() {
		long start = System.currentTimeMillis();

		File source = new File("C:\\Users\\hchaojie\\Pictures\\video\\04. 文件输入输出流.mp4");
		File target = new File("test.mp4");
		
		try (
			// 输入流，用来读文件
			FileInputStream fi = new FileInputStream(source);
			// 输出流， 用来写文件
			FileOutputStream fo = new FileOutputStream(target);
		) {
			byte[] contents = new byte[1024];
			
			while (true) {
				int count = fi.read(contents);
				if (count == -1) {
					break;
				}
				
				// 读到多少位，就写多少位
				fo.write(contents, 0, count);
			}
			
//			int count = 0;
//			while ((count = fi.read(contents)) != -1) {
//				fo.write(contents, 0, count);
//			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		long end = System.currentTimeMillis();
		System.out.println("耗时：" + (end - start));
	}
}
